﻿using System.Text.RegularExpressions;
using System.Xml.Linq;
using PengSW.NotifyPropertyChanged;
using PengSW.XmlHelper;
using static PengSW.XmlHelper.XmlLinqHelper;
using static PengSW.RuntimeLog.RL;
using System;

namespace ProtocolAnalyzer
{
    public class AutoResponse : NotifyPropertyChangedObject, IXmlSeriable
    {
        public string ReceivedPattern { get => _ReceivedPattern; set { SetValue(ref _ReceivedPattern, value, nameof(ReceivedPattern)); _Regex = null; } }
        private string _ReceivedPattern;

        public string ResponsePattern { get => _ResponsePattern; set { SetValue(ref _ResponsePattern, value, nameof(ResponsePattern)); _Regex = null; } }
        private string _ResponsePattern;
        
        private Regex _Regex = null;

        public string GetResponse(string aReceivedText)
        {
            try
            {
                if (_Regex == null) _Regex = new Regex(ReceivedPattern);
                if (!_Regex.IsMatch(aReceivedText)) return null;
                return _Regex.Replace(aReceivedText, ResponsePattern);
            }
            catch (Exception ex)
            {
                E(ex, "GetResponse");
                return null;
            }
        }

        public void ReadFromXml(XElement aXElement)
        {
            if (aXElement == null) return;
            ReceivedPattern = aXElement.GetAttributeValue(nameof(ReceivedPattern), "");
            ResponsePattern = aXElement.GetAttributeValue(nameof(ResponsePattern), "");
        }

        public XElement CreateXElement(string aXmlNodeName)
        {
            return new XElement(aXmlNodeName, CreateXAttribute(nameof(ReceivedPattern), ReceivedPattern), CreateXAttribute(nameof(ResponsePattern), ResponsePattern));
        }
    }
}
